import Vue from "vue";
import Vuex from "vuex";
import createPersistedState from "vuex-persistedstate";
Vue.use(Vuex);

export default new Vuex.Store({
  plugins: [createPersistedState()],
  state: {
    todos: JSON.parse(localStorage.getItem("vuex") || "[]"),
    activeTab: "all",
  },
  getters: {
    activeTab:function(state){
      return state.activeTab;
    },
    // 剩下项目
    remaining: function (state) {
      let remainingTodos = state.todos.filter((v) => {
        // return !v.status // false => 返回
        if (!v.status) {
          return true;
        }
      });
      return remainingTodos.length;
    },
    allChecked: function (state) {
      let checked = true;
      // 只要todo 里面有一个 status false => allChecked = false
      state.todos.map((v) => {
        if (!v.status) checked = false;
      });
      return checked;
    },
    filterTodos: function (state) {
      // all active completed
      console.log(state.todos);
      if (state.activeTab === "all") {
        return state.todos;
      } else if (state.activeTab === "active") {
        return state.todos.filter((v) => {
          // v.status => false
          return !v.status;
        });
      } else if (state.activeTab === "completed") {
        return state.todos.filter((v) => {
          // v.status => true
          return v.status;
        });
      }
    },
  },
  mutations: {
    handleClearCompleted:function(state){
            // 筛选出未完成 => todos
      let activeTodos = state.todos.filter((v) => {
        // v.status => false
        return !v.status; // false => !false => true
      });
      state.todos = activeTodos;
    },
    changeActiveTab: function (state, { payload }) {
      state.activeTab = payload.activeTab;
    },
    deletTodo: function (state, { payload }) {
      state.todos.splice(payload.index, 1);
    },
    addTodo: function (state, { payload }) {
      state.todos.push(payload);
    },
    // 全选逻辑
    allCheck: function (state) {
      state.todos.map((v) => {
        v.status = true;
      });
      console.log(state.todos);
    },
  },
  actions: {},
  modules: {},
});
